const rp = require("request-promise");
module.exports = class extends think.Controller {
  /**
   * 小程序用户登录
   * @returns {Promise<*>}
   */
  async loginAction() {
    const js_code = this.post("js_code");
    const user = this.model("user");
    // 获取openid
    const options = {
      method: "GET",
      url: "https://api.weixin.qq.com/sns/jscode2session",
      qs: {
        grant_type: "authorization_code",
        js_code: js_code,
        secret: think.config("xcx.secret"),
        appid: think.config("xcx.appid"),
      },
    };

    let sessionData = await rp(options);
    sessionData = JSON.parse(sessionData);
    let data = {
      user_id: 1,
      session_key: sessionData.session_key,
      openid: sessionData.openid,
    };
    // let userInfo = await user.field('id as user_id,uuid').where(wh).find();
    // if (think.isEmpty(userInfo)) {
    //     data.uuid = think.uuid('v4');
    //     const user_id = await user.add({
    //         uuid: data.uuid,
    //         username: '微信用户' + think.uuid('v2').substr(0, 10),
    //         openid: data.openid
    //     });
    //     data.user_id = user_id;
    // } else {
    //     data.user_id = userInfo.user_id;
    //     data.uuid = userInfo.uuid;
    // }

    let users = await user.where({ openid: sessionData.openid }).find();
    if (think.isEmpty(users)) {
      users = { login: 0 };
    } else {
      data.user_id = users.id;
      data.uuid = users.uuid;
      data.phone = users.phone;
    }
    const TokenSerivce = this.service("token");
    const xiaoju_token = await TokenSerivce.create(data);

    if (think.isEmpty(xiaoju_token)) {
      return this.fail("登录失败");
    }
    return this.success({ xiaoju_token: xiaoju_token, userInfo: users });
  }
};
